package com.linkdood.app.security;

import com.linkdood.app.domain.Account;
import com.linkdood.app.service.AccountService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 通过用户名认证用户
 * @author YunJ
 */
@Slf4j
@Component("userDetailsService")
public class UserModelDetailsServiceImpl implements UserDetailsService {

    private final AccountService accountService;

    public UserModelDetailsServiceImpl(AccountService accountService) {
        this.accountService = accountService;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserDetails loadUserByUsername(final String login) {
        log.debug("Authenticating user '{}'", login);
        List<Account> accounts = accountService.listAccountByUserName(login);
        if (CollectionUtils.isEmpty(accounts)) {
            throw new UsernameNotFoundException("User with email " + login +
                    " was not found in the database");
        }
        Account account = accounts.get(0);
        return createSpringSecurityUser(account);
    }

    private User createSpringSecurityUser(Account account) {
        String[] roles = new String[1];
        roles[0] = account.getRole();
        List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(roles);
        return new User(account.getId(), account.getPassword(), authorities);
    }
}
